package a08_回溯算法;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * <p>
 * a03_组合优化复习0
 * </p>
 *
 * @author flyduck
 * @since 2025/1/6
 */
public class a03_组合优化复习0 {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        LinkedList<Integer> path = new LinkedList<>();
        traversal(result, path, n, k, 1);
        return result;
    }

    private void traversal(List<List<Integer>> result,
                           LinkedList<Integer> path,
                           int n,
                           int k,
                           int startIdx){
        if (path.size() == k) {
            result.add(new ArrayList<>(path));
            return;
        }

        //比如n=9
        //1,2,3,4,5,6,7,8,9
        //k=5
        //假设path里面有2个了
        //差3个 k - path.size
        //那么i从1开始可以
        //那么i从2开始可以
        //那么i从7开始可以
        //7 = n - (k - path.size) + 1
        for (int i = startIdx; i <= n - (k - path.size()) + 1; i++) {
            path.add(i);
            traversal(result, path, n, k, i + 1);
            path.removeLast();
        }
    }
}
